package com.tinama.jedis01.cas;



import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author lgc
 * @createDate 2020/10/16 - 10:04
 */
public class Deadlock {
    public static void main(String[] args){
        MyThreads myThread = new MyThreads();
        myThread.isFlag=true;


        new Thread(()->myThread.run(),"T1").start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        myThread.isFlag=false;
        new Thread(()->myThread.run(),"T2").start();

    }
}
class MyThreads{
    /**
    *
    */
    private String lockA ="lockA";
    private String lockB ="lockB";
    public boolean isFlag;

    public void run(){
        if (isFlag) {
            synchronized (lockA) {
                try {
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(3000);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                synchronized (lockB) {
                    System.out.println("按lock1->lock2的顺序执行代码");
                }
            }
        }else {
            synchronized (lockB) {
                try {
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(3000);

                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                synchronized (lockA) {
                    System.out.println("按lock2->lock1顺序执行代码");
                }
            }
        }
    }


}
